package com.example.scribe.backend.handlers;

import com.example.scribe.SyntaxNode;
import com.example.scribe.backend.BytecodeOps;
import com.example.scribe.backend.ExpressionNodeHandler;
import com.example.scribe.backend.LocalVariableAllocator;
import net.bytebuddy.implementation.bytecode.StackManipulation;

/**
 * Handler for identifier expressions (local variables and parameters).
 */
public final class IdentifierExpressionHandler implements ExpressionNodeHandler {
    @Override
    public boolean canHandle(String nodeType) {
        return "identifier".equals(nodeType) || "Identifier".equals(nodeType);
    }

    @Override
    public StackManipulation handle(SyntaxNode node, String generatedClassName, LocalVariableAllocator locals) {
        if (node == null || node.text() == null) {
            return StackManipulation.Trivial.INSTANCE;
        }
        
        String name = node.text();
        if (locals.hasName(name)) {
            return BytecodeOps.loadInt(locals.getIndexByName(name));
        }
        
        // Not a local/parameter, return Trivial to allow other handlers to process
        return StackManipulation.Trivial.INSTANCE;
    }
}

